<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item label="昵称" prop="nickname" ref="nickname">
      <el-input v-model="form.nickname" placeholder="请输入昵称" @keyup.enter.native="signUp" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone" ref="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号" type="number" />
    </el-form-item>
    <el-form-item label="密码" prop="password" ref="password">
      <el-input v-model="form.password" placeholder="请输入密码" show-password />
    </el-form-item>
    <el-form-item label="验证码" prop="code" ref="code">
      <el-input v-model="form.code" placeholder="请输入验证码" @keyup.enter.native="signUp">
        <send-code-btn
          slot="suffix"
          :phone="form.phone"
          @checkPhone="checkPhone"
          class="m-r-10"
        />
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button class="full" type="primary" @click="signUp" :loading="loading">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import { formatUser } from '@/views/users/format';
import SendCodeBtn from '@/components/shared/SendCodeBtn';

export default {
  name: 'sign-up-form',
  components: { SendCodeBtn },
  data() {
    return {
      form: {
        nickname: '',
        phone: '',
        password: '',
        code: '',
      },
      rules: {
        nickname: [{ required: true, validator: this.$va.nickname, trigger: 'blur' }],
        phone: [{ required: true, validator: this.$va.phone, trigger: 'blur' }],
        password: [{ required: true, validator: this.$va.password, trigger: ['blur', 'change'] }],
        code: [{ required: true, validator: this.$va.code, trigger: 'blur' }],
      },
      loading: false,
    };
  },
  computed: {
    signUpParams() {
      // 取消了密码验证
      return Object.assign({}, this.form, { rePassword: this.form.password });
    },
  },
  methods: {
    ...mapActions({ setCurUser: 'setCurrentUser' }),
    // 注册
    signUp() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.users.signUp(this.signUpParams)
            .then((res) => {
              this.$message.success('注册成功');
              this.setCurUser(formatUser(res.data));
              this.$router.push('/users/edit');
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 触发验证手机号的方法
    checkPhone() {
      this.$refs.form.validateField('phone');
    },
  },
};
</script>

<style></style>
